import * as fApi from '../../../../../api/flow/flow'
import FlowRuntimeApi from '../../../../../api/flow/FlowRuntimeApi'
import { mapProcessGroup } from '../../../../../api/flow/flow'
import Utils from '../../../utils/Common'

const state = {
  processors: [],
  links: [],
  groups: [],
  flowGroupIDs: ['root'],
  allFlow: [],
  /**
   * @deprecated
   * 弃用，使用 useFlowStore （路径：import {useFlowStore} from "@/store/modules/flow/flowStore";）下的 CurrentFlow 替代
   */
  currentFlow: {}, // 流程的基本信息，不包含节点信息
  /**
   * @deprecated
   * 弃用，使用 useFlowStore （路径：import {useFlowStore} from "@/store/modules/flow/flowStore";）下的 CurrentClickNode 替代
   */
  currentClickNode: {}
}

const getters = {
  flowGroupId: state => {
    const { flowGroupIDs } = state
    return flowGroupIDs[flowGroupIDs.length - 1]
  },
  processors: state => {
    return state.processors
  },
  links: state => {
    return state.links
  },
  /**
   * 弃用，请使用 /src/store/flow/flowStore.ts 下的 AllFlow 替代
   * @deprecated
   * @param state
   * @returns {*[]}
   */
  allFlow: state => {
    return state.allFlow
  },
  getCurrentFlow: state => {
    return state.currentClickNode
  },
  getCurrentNode: state => {
    return state.currentFlow
  }
}

const mutations = {
  /**
   * 缓存所有节点信息
   * @param state
   * @param processors
   * @param links
   * @param groups
   * @constructor
   */
  SET_PROCESS_GROUP: (state, { processors, links, groups }) => {
    state.processors = processors
    state.links = links
    state.groups = groups
  },
  /**
   * 跟新节点状态信息
   * @param state
   * @param Nodes
   * @constructor
   */
// 状态管理器 mutation 中修正
  UPDATE_NODE_STATUS: (state, Node) => {
    state.processors = state.processors.map(processor => {
      if (processor.id === Node.id) {
        // 1. 深拷贝原对象，避免直接修改原引用
        const updatedProcessor = { ...processor, style: { ...processor.style } };
        // 2. 更新 runStatus（若需）
        if (Node.runStatus !== undefined) {
          updatedProcessor.runStatus = Node.runStatus;
        }
        // 3. 根据 nodeStatus 更新 style.backgroundColor（子组件依赖的属性）
        if (Node.nodeStatus) {
          updatedProcessor.nodeStatus = Node.nodeStatus;
          if (Node.nodeStatus === 'SUCCESS') {
            updatedProcessor.style.backgroundColor = '#0b9b0b'; // 修正属性路径
          } else if (Node.nodeStatus === 'ERROR') {
            updatedProcessor.style.backgroundColor = 'red';
          } else {
            updatedProcessor.style.backgroundColor = '#fff'; // 默认值
          }
        }
        return updatedProcessor; // 返回新对象触发响应式
      }
      return processor;
    });
  },
  SET_CUR_GROUP: (state, ids) => {
    state.flowGroupIDs = ids
  },
  SET_ALL_FLOW: (state, allFlow) => {
    state.allFlow = allFlow
  },
  /**
   * 更新当前流程
   *
   * @deprecated
   * 弃用，使用 useFlowStore （路径：import {useFlowStore} from "@/store/modules/flow/flowStore";）下的 SetCurrentFlow 替代
   *
   * @param state
   * @param item
   * @constructor
   */
  SET_CURRENT_FLOW: (state, item) => {
    state.currentFlow = item
  },
  /**
   * 设置当前被点击的节点
   * @deprecated 这个方法已弃用，
   * 使用 useFlowStore （路径：import {useFlowStore} from "@/store/modules/flow/flowStore";）下的 CurrentClickNode 替代
   * @param state
   * @param item
   * @constructor
   */
  SET_CURRENT_NODE: (state, item) => {
    state.currentClickNode = item
  }
}

const actions = {
  async loadAllFlow ({ commit, getters }, callback) {
    await new FlowRuntimeApi().GetAllFlowFiles((allFlow) => {
      commit('SET_ALL_FLOW', allFlow)
      if (Utils.IsEmpty(state.currentFlow)) {
        commit('SET_CURRENT_FLOW', allFlow[0])
      }
      callback(allFlow)
    })
  },

  /**
   * 开始获取当前选中的流程
   * @param commit
   * @param getters
   * @returns {Promise<void>}
   */
  getProcessGroup ({ commit, getters }) {
    const { flowGroupId } = getters
    new FlowRuntimeApi().GetCurrentFlow(null, updating => {
      if (Utils.IsEmpty(updating)) {
        return null
      }
      const ssss = Utils.GetParents(updating)
      const updated = mapProcessGroup(ssss)
      commit('SET_PROCESS_GROUP', updated)
      if (flowGroupId === 'root') {
        commit('SET_CUR_GROUP', [updated.id])
      }
    })
  },

  setProcessGroup ({ commit }, updated) {
    commit('SET_PROCESS_GROUP', updated)
  },

  /**
   * 创建一个新的节点
   * @param commit
   * @param getters
   * @param typeId
   * @param x
   * @param y
   * @param maxX
   * @param maxY
   * @returns {Promise<void>}
   */
  async newProcessor ({ commit, getters }, { typeId, x, y, maxX, maxY }) {
    const { flowGroupId } = getters
    const updated = await fApi.createProcessor(typeId, { x, y, maxX, maxY }, flowGroupId)
    commit('SET_PROCESS_GROUP', updated)
  },
  async UpdateSnippet ({ getters, commit, state }, payload) {
    const { flowGroupId } = getters
    const processors = state.processors.filter(p => payload.processors.includes(p.id))
    const groups = state.groups.filter(p => payload.groups.includes(p.id))
    fApi.UpdateSnippet(processors, groups, flowGroupId)
    // const updated = await fApi.UpdateSnippet(processors, groups, flowGroupId)
    // commit('SET_PROCESS_GROUP', updated)
  },

  /**
   * 添加新的连接
   * @param commit
   * @param getters
   * @param link
   * @returns {Promise<void>}
   */
  async newConnection ({ commit, getters }, link) {
    const { flowGroupId } = getters
    const updated = await fApi.createConnection(link, flowGroupId)
    commit('SET_PROCESS_GROUP', updated)
  },

  /**
   * 粘贴节点
   * @param state
   * @param commit
   * @param getters
   * @param payload
   * @returns {Promise<*[]>}
   */
  async cloneSnippet ({ state, commit, getters }, payload) {
    const { flowGroupId } = getters
    const SourceFlowId = payload.FlowId
    const oldids = state.processors.map(p => p.id)
    // let processors = state.processors.filter(p => payload.processors.includes(p.id))
    let processors = payload.processors
    const links = state.links.filter(l => payload.links.includes(l.id))
    const updated = await fApi.cloneSnippet({ SourceFlowId, processors, links }, flowGroupId)
    commit('SET_PROCESS_GROUP', updated)
    return updated.processors.filter(p => !oldids.includes(p.id)).map(p => p.id)
  },
  async addGroup ({ commit, state, getters }, payload) {
    const { flowGroupId } = getters
    const processors = state.processors.filter(p => payload.processors.includes(p.id))
    const links = state.links.filter(link => payload.links.includes(link.id))
    const updated = await fApi.addGroup({ processors, links }, flowGroupId)
    commit('SET_PROCESS_GROUP', updated)
  },
  async remvoeSnippet ({ commit, getters }, { processors, links, groups }) {
    const { flowGroupId } = getters
    const updated = await fApi.deleteSnippet({ processors, links, groups }, flowGroupId)
    commit('SET_PROCESS_GROUP', updated)
  },
  async ungroup ({ dispatch, commit, getters }, groupID) {
    const { flowGroupId } = getters
    const updated = await fApi.ungroup(groupID, flowGroupId)
    commit('SET_PROCESS_GROUP', updated)
  },
  async enterGroup ({ dispatch, commit, state }, groupID) {
    const { flowGroupIDs } = state
    const index = flowGroupIDs.findIndex(id => id === groupID)
    if (index < 0) {
      commit('SET_CUR_GROUP', [...flowGroupIDs, groupID])
    } else {
      commit('SET_CUR_GROUP', flowGroupIDs.slice(0, index + 1))
    }
    dispatch('getProcessGroup')
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
